<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="150px"
        v-loading="formLoading"
    >

      <el-form-item label="申请金额" prop="payMoney">
        <el-input-number v-model="formData.payMoney"/>
      </el-form-item>

      <el-form-item label="店铺" prop="shopId">
        <select-basic-shop v-model="formData.shopId" :shop-id-filter="shopIdFilter"/>
      </el-form-item>
      <el-form-item label="微信号" prop="wechat">
        <el-input v-model="formData.wechat" placeholder="请输入微信号"/>
      </el-form-item>
      <el-form-item label="手机号" prop="phoneNumber">
        <el-input v-model="formData.phoneNumber" placeholder="请输入手机号"/>
      </el-form-item>
      <el-form-item label="本月已申请金额" prop="thisMonthAppliedAmount">
        <el-input-number v-model="formData.thisMonthAppliedAmount"/>
      </el-form-item>
      <el-form-item label="上月账户余额" prop="lastMonthBalance">
        <el-input-number v-model="formData.lastMonthBalance"/>
      </el-form-item>
      <el-form-item label="本次申请账户余额" prop="theAppliedAmount">
        <el-input-number v-model="formData.theAppliedAmount"/>
      </el-form-item>
      <el-form-item label="本月补单金额合计" prop="thisMonthBusinessMoney">
        <el-input-number v-model="formData.thisMonthBusinessMoney"/>
      </el-form-item>
      <el-form-item label="应余余额" prop="remainingBalance">
        <el-input-number v-model="formData.remainingBalance" :disabled="true"/>
      </el-form-item>
      <el-form-item label="差额" prop="difference">
        <el-input-number v-model="formData.difference" :disabled="true"/>
      </el-form-item>
      <el-form-item label="微信余额截图" prop="wechatBalanceImg">
        <upload-img v-model="formData.wechatBalanceImg"/>
      </el-form-item>


      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {BusinessPay, BusinessPayApi} from '@/api/business/operation/business/pay'
import {useUserStore} from "@/store/modules/user";

/** 业务-运营-补单-账号充值 表单 */
defineOptions({name: 'BusinessPayForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  shopId: undefined,
  wechat: undefined,
  phoneNumber: undefined,
  thisMonthAppliedAmount: undefined,
  lastMonthBalance: undefined,
  theAppliedAmount: undefined,
  thisMonthBusinessMoney: undefined,
  remainingBalance: undefined,
  difference: undefined,
  wechatBalanceImg: undefined,
  payMoney: undefined,
  payTime: undefined,
  status: undefined,
  remark: undefined,
  processInstanceId: undefined
})
const formRules = reactive({
  payMoney: [{required: true, message: '申请不能为空', trigger: 'blur'}],
  shopId: [{required: true, message: '店铺不能为空', trigger: 'blur'}],
  wechat: [{required: true, message: '微信号不能为空', trigger: 'blur'}],
  phoneNumber: [{required: true, message: '手机号不能为空', trigger: 'blur'}],
  thisMonthAppliedAmount: [{required: true, message: '本月已申请金额不能为空', trigger: 'blur'}],
  lastMonthBalance: [{required: true, message: '上月账户余额不能为空', trigger: 'blur'}],
  theAppliedAmount: [{required: true, message: '本次申请账户余额不能为空', trigger: 'blur'}],
  thisMonthBusinessMoney: [{required: true, message: '本月补单金额合计不能为空', trigger: 'blur'}],
  remainingBalance: [{required: true, message: '应余余额不能为空', trigger: 'blur'}],
  difference: [{required: true, message: '差额不能为空', trigger: 'blur'}],
  wechatBalanceImg: [{required: true, message: '微信余额截图不能为空', trigger: 'change'}],
})
const formRef = ref() // 表单 Ref
const shopIdFilter = ref('')
const userStore = useUserStore()


// 监听相关字段变化，自动计算应余余额和差额
watch(
    [
      () => formData.value.thisMonthAppliedAmount,
      () => formData.value.lastMonthBalance,
      () => formData.value.thisMonthBusinessMoney,
      () => formData.value.theAppliedAmount
    ],
    ([thisMonthApplied, lastMonthBalance, thisMonthBusiness, theApplied]) => {
      // 计算应余余额 = 本月已申请金额 + 上月账户余额 - 本月补单金额
      if (thisMonthApplied !== undefined && lastMonthBalance !== undefined && thisMonthBusiness !== undefined) {
        const rawRemaining = thisMonthApplied + lastMonthBalance - thisMonthBusiness;
        // 保留两位小数（四舍五入）
        formData.value.remainingBalance = Number(rawRemaining.toFixed(2));
      } else {
        formData.value.remainingBalance = undefined;
      }

      // 计算差额 = 本次申请账户余额 - 应余余额
      if (theApplied !== undefined && formData.value.remainingBalance !== undefined) {
        const rawDifference = theApplied - formData.value.remainingBalance;
        // 保留两位小数（四舍五入）
        formData.value.difference = Number(rawDifference.toFixed(2));
      } else {
        formData.value.difference = undefined;
      }
    },
    {immediate: true} // 初始化时立即执行一次
)

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BusinessPayApi.getBusinessPay(id)
    } finally {
      formLoading.value = false
    }
  }
  if (!formData.value.shopId) {
    const shopIds = userStore.user.shopIds
    shopIdFilter.value = userStore.user.shopIds
    // 先判断 shopIds 存在且不是空字符串，再进行分割
    if (shopIds && typeof shopIds === 'string' && shopIds.trim() !== '') {
      formData.value.shopId = shopIds.split(',')[0];
    }
  }
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as BusinessPay
    if (formType.value === 'create') {
      await BusinessPayApi.createBusinessPay(data)
      message.success(t('common.createSuccess'))
    } else {
      await BusinessPayApi.updateBusinessPay(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    shopId: undefined,
    wechat: undefined,
    phoneNumber: undefined,
    thisMonthAppliedAmount: undefined,
    lastMonthBalance: undefined,
    theAppliedAmount: undefined,
    thisMonthBusinessMoney: undefined,
    remainingBalance: undefined,
    difference: undefined,
    wechatBalanceImg: undefined,
    payMoney: undefined,
    payTime: undefined,
    status: undefined,
    remark: undefined,
    processInstanceId: undefined
  }
  formRef.value?.resetFields()
}
</script>
